var ws = new WebSocket('ws://echo.websocket.org');
ws.onopen = function(){
    document.getElementById("text").innerHTML = "connected \n";
}

ws.onmessage = function(e){
    if(typeof e.data == "object"){
        var uri = URL.createObjectURL(e.data);
        var img = document.createElement("img"); 
        img.src = uri;
        img.setAttribute('width', '50px');
        document.getElementById('images').appendChild(img);
    }else if(typeof e.data == "string"){
        document.getElementById("text").innerHTML +=  e.data + "\n";
    }
}

function sendMessage(){
    msg = document.getElementById("texttosend").value;
    document.getElementById("texttosend").value = "";
    ws.send(msg);
}
document.addEventListener("DOMContentLoaded", function(event) {
    var dropzone = document.getElementById("main");
    
    dropzone.addEventListener('dragenter', function (e) { 
        e.stopPropagation(); 
        e.preventDefault(); 
    }, false); 

    dropzone.addEventListener('dragleave', function (e) { 
        e.stopPropagation(); 
        e.preventDefault(); 

    }, false) 
    dropzone.addEventListener('dragover', function (e) { 
        e.stopPropagation(); 
        e.preventDefault(); 
    }, false) 

    // When a file/files are dropped, deal with the file/files 
    dropzone.addEventListener('drop', function (e) { 
        e.stopPropagation(); 
        e.preventDefault(); 
        dealWithFile(e.dataTransfer.files[0]); 
    }, false); 
});

function dealWithFile(file){
    document.getElementById("text").innerHTML += "uploadFile : " + file.name + "\n";
    var reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function() {
        console.log("sending: " + file.name);
        ws.send(reader.result);
    }
}